#include "stdafx.h"
#include "base/common.h"
#include "base/win32.h"
#include "render.h"

namespace uiwin
{
	Clip::~Clip()
	{
		ASSERT(::GetObjectType(hDC) == OBJ_DC || ::GetObjectType(hDC) == OBJ_MEMDC);
		ASSERT(::GetObjectType(hRgn) == OBJ_REGION);
		ASSERT(::GetObjectType(hOldRgn) == OBJ_REGION);

		::SelectClipRgn(hDC, hOldRgn);
		::DeleteObject(hOldRgn);
		::DeleteObject(hRgn);
	}

	void Clip::GenerateClip(HDC hdc, RECT rc, Clip& clip)
	{
		RECT rclip = {0};
		::GetClipBox(hdc, &rclip);

		clip.hOldRgn = ::CreateRectRgnIndirect(&rclip);
		clip.hRgn = ::CreateRectRgnIndirect(&rc);
		::ExtSelectClipRgn(hdc, clip.hRgn, RGN_AND);
		clip.hDC = hdc;
		clip.rcItem = rc;
	}

	void Clip::GenerateRoundClip(HDC hdc, RECT rc, RECT rcitem, int width, int height, Clip& clip)
	{
		RECT rclip = {0};
		::GetClipBox(hdc, &rclip);

		clip.hOldRgn = ::CreateRectRgnIndirect(&rclip);
		clip.hRgn = ::CreateRectRgnIndirect(&rc);
		HRGN hrgnItem = ::CreateRoundRectRgn(rcitem.left, rcitem.top, 
			rcitem.right + 1, rcitem.bottom + 1, width, height);
		::CombineRgn(clip.hRgn, clip.hRgn, hrgnItem, RGN_AND);
		::ExtSelectClipRgn(hdc, clip.hRgn, RGN_AND);
		clip.hDC = hdc;
		clip.rcItem = rc;
		::DeleteObject(hrgnItem);
	}

	void Clip::UseOldClipBegin()
	{
		::SelectClipRgn(hDC, hOldRgn);
	}

	void Clip::UseOldClipEnd()
	{
		::SelectClipRgn(hDC, hRgn);
	}
}